<template>
  <div class="article-container page-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      fixed
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    >
    </van-nav-bar>
    <div class="article-wrap">
      <h1 class="title">{{ article.title }}</h1>
      <van-cell center class="user-info">
        <div slot="title" class="name">{{ article.aut_name }}</div>
        <van-image
          class="avatar"
          slot="icon"
          fit="cover"
          round
          :src="article.aut_photo"
        ></van-image>
        <div slot="label" class="pubdate">
          {{ article.pubdate | relativeTime }}
        </div>
        <van-button
          class="follow-btn"
          :type="article.is_followed ? 'default' : 'info'"
          :icon="article.is_followed ? '' : 'plus'"
          round
          size="small"
          :loading="isFollowLoading"
          @click="onFollow"
        >
          {{ article.is_followed ? "已关注" : "关注" }}
        </van-button>
      </van-cell>
      <div
        class="content markdown-body"
        v-html="article.content"
        ref="article-content"
      ></div>
      <!-- 文章评论列表 -->
    <comment-list
      :source="articleId"
      :list="CommentList"
      @update-total-count="totalCommentCount = $event"
      @reply-click="onReplyClick"
    ></comment-list>
    </div>
    <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button
        class="write-btn"
        type="default"
        round
        size="small"
        @click="isPostShow = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :info="totalCommentCount" color="#777"></van-icon>
      <van-icon
        :name="article.is_collected ? 'star' : 'star-o'"
        :color="article.is_collected ? 'orange' : '#777'"
        @click="onCollect"
      ></van-icon>
      <van-icon
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        :color="article.attitude === 1 ? 'hotpink' : '#777'"
        @click="onLike"
      ></van-icon>
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- 发布评论 -->
    <van-popup
      v-model="isPostShow"
      position="bottom"
    >
      <post-comment
        :target="articleId"
        @post-success="onPostSuccess"
        ></post-comment>
    </van-popup>

    <!-- 评论回复 -->
    <van-popup
      v-model="isReplyShow"
      position="bottom"
    >
    <!-- 这里使用v-if是为了让组件随着弹出层的显示与隐藏进行渲染和销毁
    防止加载过的组件不重新渲染导致数据不会重新加载 -->
    <comment-reply
      v-if="isReplyShow"
      :comment="replyComment"
      :articleId="articleId"
      @close="isReplyShow = false"
    ></comment-reply>
    </van-popup>
  </div>
</template>

<script>
import {
  getArticleById,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike
} from '@/api/articles'
import { ImagePreview } from 'vant'
import { deleteFollow, addFollow } from '@/api/user'
import CommentList from './components/comment-list.vue'
import PostComment from './components/post-comment.vue'
import CommentReply from './components/comment-reply.vue'
export default {
  name: 'ArticlePage',
  props: {
    articleId: {
      type: [String, Number, Object],
      required: true
    }
  },
  components: {
    CommentList,
    PostComment,
    CommentReply
  },
  data () {
    return {
      // 控制加载中的 loading 状态
      loading: true,
      // 文章数据对象
      article: {},
      // 关注用户的 loading 状态
      isFollowLoading: false,
      // 控制是否显示发布评论
      isPostShow: false,
      // 控制是否显示回复评论
      isReplyShow: false,
      // 文章评论列表
      CommentList: [],
      // 评论总数量
      totalCommentCount: 0,
      // 当前回复评论
      replyComment: {}
    }
  },
  created () {
    this.loadArticle()
  },
  mounted () {},
  methods: {
    async loadArticle () {
      const { data } = await getArticleById(this.articleId)
      // console.log(data)
      this.article = data.data
      this.$nextTick(() => {
        this.handlePerviewImage()
      })
    },
    handlePerviewImage () {
      // 1. 获取文章内容 dom 容器
      const articleContent = this.$refs['article-content']
      // 数据改变影响视图更新 (DOM 数据) 不是立即的
      // 所以如果需要在修改数据之后马上操作被该数据影响的视图 DOM
      // 需要把这个代码放到 $newxtTick 中

      // 2. 得到所有 img 标签
      const imgs = articleContent.querySelectorAll('img')
      const imgPaths = []
      // 3. 循环 img 列表 给 img 注册点击事件
      imgs.forEach((img, index) => {
        imgPaths.push(img.src)
        img.onclick = function () {
          // 4. 在事件处理函数中调用 ImagePreview() 预览
          ImagePreview({
            // 预览图片路径列表
            images: imgPaths,
            // 起始位置
            startPosition: index
          })
        }
      })
    },
    async onFollow () {
      this.isFollowLoading = true
      if (this.article.is_followed) {
        // 已经关注，取消关注
        await deleteFollow(this.article.aut_id)
      } else {
        // 没有关注，添加关注
        await addFollow(this.article.aut_id)
      }
      // 更新视图
      this.article.is_followed = !this.article.is_followed
      this.isFollowLoading = false
    },
    async onCollect () {
      this.$toast.loading({
        message: '操作中...',
        // 禁止背景点击
        forbidClick: true
      })
      if (this.article.is_collected) {
        // 已经收藏，取消收藏
        await deleteCollect(this.articleId)
      } else {
        // 没有收藏，添加收藏
        await addCollect(this.articleId)
      }
      // 更新视图
      this.article.is_collected = !this.article.is_collected
      this.$toast.success(`${this.article.is_collected ? '' : '取消'}收藏成功`)
    },
    async onLike () {
      this.$toast.loading({
        message: '操作中...',
        // 禁止背景点击
        forbidClick: true
      })
      if (this.article.attitude === 1) {
        // 已经点赞，取消点赞
        await deleteLike(this.articleId)
        this.article.attitude = -1
      } else {
        // 没有点赞，添加点赞
        await addLike(this.articleId)
        this.article.attitude = 1
      }
      this.$toast.success(
        `${this.article.attitude === 1 ? '' : '取消'}点赞成功`
      )
    },
    // 发布评论
    onPostSuccess (comment) {
      // console.log(comment)
      // 把发布评论成功的数据对象放到评论列表顶部
      this.CommentList.unshift(comment)
      // 更新评论的总数量
      this.totalCommentCount++
      // 关闭发布评论弹出层
      this.isPostShow = false
    },
    // 发布回复
    onReplyClick (comment) {
      console.log('onReplyClick', comment)

      this.replyComment = comment
      // 展示回复内容
      this.isReplyShow = true
    }
  }
}
</script>

<style scoped lang="less">
@import url("./github-markdown.css");
.article-wrap {
  position:fixed;
  left: 0;
  right: 0;
  top: 46px;
  bottom: 44px;
  overflow-y: auto;
}
.title {
  font-size: 20px;
  color: #3a3a3a;
  padding: 14px;
  background-color: #fff;
  margin: 0;
}
.user-info {
  .avatar {
    width: 35px;
    height: 35px;
    margin-right: 8px;
  }
  .name {
    font-size: 12px;
    color: #333333;
  }
  .pubdate {
    font-size: 11px;
    color: #b4b4b4;
  }
  .follow-btn {
    width: 85px;
    height: 29px;
  }
}
ul {
  list-style: unset;
}
.article-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 44px;
  border-top: 1px solid #d8d8d8;
  background-color: #fff;
  .write-btn {
    width: 141px;
    height: 23px;
    border: 1px solid #eeeeee;
    font-size: 15px;
    line-height: 23px;
    color: #a7a7a7;
  }
  .van-icon {
    font-size: 20px;
  }
  .comment-icon {
    bottom: -2px;
  }
  .share-icon {
    bottom: -2px;
  }
}
.markdown-body {
  padding: 14px;
  background-color: #fff;
}
</style>
